<template>
  <popup
    class="popup"
    v-model:visible="isVisibleRiderTakingOrderSetter"
    height="70%"
    transparency="70%"
    background="#f5f5f5"
  >
    <template #content>
      <view class="content">
        <piece>
          <view class="piece-item">
            <view class="left">允许系统派单</view>
            <view class="right">
              <switch
                :checked="riderSettings?.systemDispatch == 1"
                color="#FFCC33"
                :disabled="true"
                style="transform: scale(0.8)"
                @click="systemDispatchChange"
              />
            </view>
          </view>
          <view class="piece-item">
            <view class="left">最大接单量</view>
            <view class="right">
              <uni-number-box v-model="preMaxTakingOrder" @change="maxTakingOrderChange" />
            </view>
          </view>
        </piece>
        <piece margin-top="20rpx">
          <view class="piece-item" @click="toSelectRiderWorkRegion">
            <view class="left">常驻地址</view>
            <view class="right">
              <span class="region-desc">{{ riderWorkRegion.districtName + riderWorkRegion.detailAddress }}</span>
              <uni-icons type="right" size="18"></uni-icons>
            </view>
          </view>
        </piece>
      </view>
    </template>
  </popup>
</template>

<script setup lang="ts">
import $store from '@/store'
import { ref, watch } from 'vue'
import Popup from '@/components/popup/index.vue'
import Piece from '@/components/piece/index.vue'
import RiderSetting from '@/types/entity/RiderSettings'
import $API from '@/api'
import { $modal } from '@/plugins'
import RiderWorkRegion from '@/types/entity/RiderWorkRegion'
import PropertiesCopyUtils from '@/utils/PropertiesCopyUtils'
import LocationInfo from '@/types/entity/LocationInfo'
const isVisibleRiderTakingOrderSetter = ref(false)
const riderSettings = $store.user.riderSettings
const riderWorkRegion = ref(new RiderWorkRegion())
const preMaxTakingOrder = ref(0)
// 当riderSettings中的值改变时同步到preMaxTakingOrder
watch(
  () => riderSettings.value.maxTakingOrder,
  (newVal, oldVal) => (preMaxTakingOrder.value = newVal),
  { immediate: true }
)
async function maxTakingOrderChange() {
  // 保存目标值为副本
  const targetPreMaxTakingOrder = preMaxTakingOrder.value
  // 恢复回来
  preMaxTakingOrder.value = riderSettings.value.maxTakingOrder
  // 更新
  await $API.riderSettings.update({ maxTakingOrder: targetPreMaxTakingOrder })
  // 修改成功，修改同步到对象中的maxTakingOrder
  riderSettings.value.maxTakingOrder = preMaxTakingOrder.value = targetPreMaxTakingOrder
}
const isInitializedSettingInfo = ref(false)
// 监听打开update settings 事件
$store.user.openOrderTakingSettingsEvent.on(async () => {
  // 查询用户信息
  if (!isInitializedSettingInfo.value) {
    const queryRiderWorkRegion = await $API.riderWorkRegion.queryRiderWorkRegion()
    riderWorkRegion.value = queryRiderWorkRegion.data
    isInitializedSettingInfo.value = true
  }
  // 让弹框可见
  isVisibleRiderTakingOrderSetter.value = true
})
// 更新系统派单状态
async function systemDispatchChange() {
  const switchAfterTargetStatus = riderSettings.value!.systemDispatch == 1 ? 0 : 1
  const updateSystemDispatchStatusResult = await $API.riderSettings.update({ systemDispatch: switchAfterTargetStatus })
  if (!updateSystemDispatchStatusResult.success) {
    $modal.toastErrorMsg(updateSystemDispatchStatusResult.message)
  } else {
    riderSettings.value!.systemDispatch = switchAfterTargetStatus
  }
}
// 选择新的常驻区域
function toSelectRiderWorkRegion() {
  uni.authorize({
    scope: 'scope.userLocation',
    success: (success) => {
      uni.chooseLocation({
        latitude: riderWorkRegion.value!.latitude,
        longitude: riderWorkRegion.value!.longitude,
        success: async function (res) {
          const result = await $API.thirdParty.parseGEO(res.longitude, res.latitude)
          const locationInfo = PropertiesCopyUtils.copy([result], new LocationInfo())
          const updateRiderWorkRegionResult = await $API.riderWorkRegion.updateRiderWorkRegion(locationInfo)
          if (!updateRiderWorkRegionResult.success) {
            $modal.toastErrorMsg(updateRiderWorkRegionResult.message)
          } else {
            // 更新成功，更新显示
            riderWorkRegion.value = { ...riderWorkRegion.value, ...result }
          }
        }
      })
    }
  })
}
</script>

<style scoped lang="scss">
.content {
  position: absolute;
  padding: 30px 25rpx 10px;
  inset: 0;

  .piece-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20rpx;
    width: 100%;
    height: 50px;
    box-sizing: border-box;
    line-height: 50px;

    .left {
      font-weight: 700;
    }

    .right {
      display: flex;
      flex-grow: 1;
      justify-content: flex-end;
      margin-left: 25rpx;

      .region-desc {
        overflow: hidden;
        width: 0;
        font-size: 28rpx;
        text-align: right;
        text-overflow: ellipsis;
        white-space: nowrap;
        flex-grow: 1;
        direction: rtl;
      }
    }
  }
}
</style>
